<template>
  <div class="order">
    <header class="page-header">
      <div class="search-bar">
        <input type="text" class="search-input" placeholder="美式">
      </div>
      <div class="shop-info">
        <h2>湖南开放大学店</h2>
        <p class="business-hours">距离您 199m</p>
      </div>
    </header>
    <main class="menu-content">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else class="menu-layout">
        <aside class="category-nav">
          <div
            v-for="(category, index) in categories"
            :key="index"
            class="nav-item"
            :class="{ active: currentCategory === index }"
            @click="selectCategory(index)"
          >
            {{ category }}
          </div>
        </aside>
        <div class="menu-items">
          <div class="menu-item" v-for="item in filteredMenuItems" :key="item.id" @click="router.push(`/shopping/detail/${item.id}`)">
            <div class="item-image placeholder">
              <img v-if="item.image" :src="`http://localhost:3005/${item.image}`" :alt="item.title">
            </div>
            <div class="item-details">
              <p class="description" style="font-weight: 700;">{{ item.title }}</p>
              <div class="tags">
                <span class="tag">人气王</span>
                <span class="tag">冷热可选</span>
              </div>
              <div class="item-footer">
                <span class="price">{{ item.price }}</span>
                <button class="add-btn" @click.stop="addToCart(item)">+</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.order {
  background-color: #f7f7f7;
  padding: 0 0 64px 0;
}

.page-header {
  margin-bottom: 0;
  padding: 15px;
  background: #fff;
}

.shop-info {
  padding: 0;
  box-shadow: none;
  background: transparent;
}

.shop-info h2 {
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 4px;
}

.shop-info h2::after {
  content: '>';
  color: #999;
}

.business-hours {
  margin: 4px 0 0;
  font-size: 12px;
  color: #999;
}

.menu-layout {
  display: flex;
  min-height: calc(80vh - 120px);
  margin: 0;
  background: #fff;
  overflow-y: auto;
}

.category-nav {
  width: 85px;
  background: #f8f8f8;
  border-radius: 0;
  padding: 0;
  position: sticky;
  top: 0;
  height: fit-content;
}

.nav-item {
  padding: 16px 8px;
  text-align: center;
  font-size: 13px;
  color: #333;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-item.active {
  color: #e4393c;
  font-weight: bold;
  background: #fff;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background-color: #e4393c;
  transform: scaleX(1);
  transition: transform 0.3s ease;
}

.nav-item:hover {
  color: #e4393c;
}

.menu-items {
  flex: 1;
  padding: 12px 12px 0;
  gap: 20px;
  background: #fff;
}

.menu-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  transition: transform 0.2s ease;
}

.item-image.placeholder {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 16px;
  background: #f8f8f8;
}

.item-image.placeholder img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
  min-width: 0;
}

.item-details h3 {
  font-size: 18px;
  color: #333;
  font-weight: 500;
  margin: 0 0 8px;
}

.tags {
  margin: 4px 0;
  display: flex;
  gap: 4px;
}

.tag {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
  background: #fff2f2;
  color: #e4393c;
  border: 1px solid #ffdbdb;
  font-weight: 500;
}

.description {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.price {
  color: #e4393c;
  font-size: 20px;
  font-weight: 500;
}

.price::before {
  content: '¥';
  font-size: 12px;
  margin-right: 1px;
}

.add-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #e4393c;
  color: white;
  border: none;
  font-size: 20px;
  line-height: 1;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.add-btn:hover {
  background: #e4393c;
  transform: none;
}

.search-bar {
  padding: 8px 15px;
  background: #f7f7f7;
  display: flex;
  align-items: center;
}

.search-input {
  background: #f2f2f2;
  border: none;
  border-radius: 16px;
  padding: 8px 12px;
  width: 100%;
  font-size: 14px;
  color: #333;
}

.search-input::placeholder {
  color: #999;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  color: #666;
}


</style>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useCartStore } from '../stores/cart'
import { useRouter } from 'vue-router'

const router = useRouter()

interface MenuItem {
  id: number
  title: string
  content: string
  price: number
  image?: string
}

const cartStore = useCartStore()
const menuItems = ref<MenuItem[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

// 添加商品分类数据
const categories = ref(['全部', '咖啡', '甜点', '轻食', '饮品', '礼品'])
const currentCategory = ref(0)

// 根据当前分类过滤商品
const filteredMenuItems = computed(() => {
  if (currentCategory.value === 0) {
    return menuItems.value
  }
  return menuItems.value.filter(item => {
    // 根据商品标题和描述内容进行分类匹配
    const categoryName = categories.value[currentCategory.value].toLowerCase()
    return item.title.toLowerCase().includes(categoryName) || 
           item.content.toLowerCase().includes(categoryName)
  })
})

const selectCategory = (index: number) => {
  currentCategory.value = index
}

const fetchMenuItems = async () => {
  try {
    const response = await fetch('http://localhost:3005/cart/list', {
      method: 'POST'
    })
    if (!response.ok) {
      throw new Error(`获取商品列表失败: ${response.status} ${response.statusText}`)
    }
    const data = await response.json()
    if (!data || typeof data.success === 'undefined') {
      throw new Error('服务器返回数据格式错误')
    }
    if (data.success === '成功' && Array.isArray(data.result)) {
      menuItems.value = data.result.map((item: { id: number; title: string; content: string; price: string; image?: string }) => ({
        id: item.id,
        title: item.title || '未知商品',
        content: item.content || '暂无描述',
        price: Number(item.price) || 0,
        image: item.image
      }))
    } else {
      throw new Error(data.msg || '获取商品列表失败')
    }
  } catch (err) {
    console.error('获取商品列表错误:', err)
    error.value = err instanceof Error ? err.message : '获取商品列表失败'
  } finally {
    loading.value = false
  }
}

const addToCart = (item: MenuItem) => {
  cartStore.addToCart(item)
}

onMounted(() => {
  fetchMenuItems()
  cartStore.loadCartFromStorage()
})
</script>